package com.upf1sh.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.upf1sh.bean.ChickenFarmInfo;
import com.upf1sh.bean.RebootData;
import com.upf1sh.mapper.ChickenFarmInfoMapper;
import com.upf1sh.service.IChickenFarmInfoService;
import com.upf1sh.utils.Result;
import org.apache.http.HttpEntity;
import org.apache.http.entity.*;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
/**
 * @Description:
 * @Title: ChickenFarmInfoController
 * @Package com.upf1sh.controller
 * @Author: ZhaoXu
 * @CreateTime: 2025/2/19 20:51
 */
@RestController
@RequestMapping("/system/info")
public class ChickenFarmInfoController
{
    @Autowired
    private IChickenFarmInfoService chickenFarmInfoService;
    @Autowired
    private ChickenFarmInfoMapper chickenFarmInfoMapper;

    /**
     * 查询养鸡场相关信息列表
     */
    @GetMapping("/list")
    public Result list(ChickenFarmInfo chickenFarmInfo)
    {

        IPage<ChickenFarmInfo> list = chickenFarmInfoService.getPage(chickenFarmInfo);
        return  Result.ok().data("data", list);
    }

    /**
     * 导出养鸡场相关信息列表
     */
      @GetMapping("/export")
      public void exportCsv(HttpServletResponse response) throws IOException
    {

        List<ChickenFarmInfo> list = chickenFarmInfoMapper.selectList(null);

        // 设置响应头
        response.setContentType("text/csv");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("数据.csv", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName);
        EasyExcel.write(response.getOutputStream(), ChickenFarmInfo.class)
                .excelType(ExcelTypeEnum.CSV)
                .sheet("数据")
                .doWrite(list);
    }


    /**
     * 获取养鸡场相关信息详细信息
     */
   @GetMapping(value = "/{id}")
    public  Result getInfo(@PathVariable("id") Long id)
    {
        return  Result.ok().data("data",chickenFarmInfoService.selectChickenFarmInfoById(id));
    }

    /**
     * 新增养鸡场相关信息
     */
     @PostMapping
    public  Result add(@RequestBody ChickenFarmInfo chickenFarmInfo)
    {
        return  Result.ok().data("data",chickenFarmInfoService.insertChickenFarmInfo(chickenFarmInfo));
    }

    /**
     * 修改养鸡场相关信息
     */
      @PutMapping
    public  Result edit(@RequestBody ChickenFarmInfo chickenFarmInfo)
    {
        return  Result.ok().data("data",chickenFarmInfoService.updateChickenFarmInfo(chickenFarmInfo));
    }

    /**
     * 删除养鸡场相关信息
     */
    @DeleteMapping("/{ids}")
    public  Result remove(@PathVariable Long[] ids)
    {
        return  Result.ok().data("data",chickenFarmInfoService.deleteChickenFarmInfoByIds(ids));
    }

    @PostMapping("/useApis")
    public Result useApis(@RequestParam("file") MultipartFile file) {
        String url = "http://newvetai.world-tech.com.cn:8092/warn/";

        // 创建临时文件
        File tempFile;
        try {
            tempFile = File.createTempFile("temp", null);
            file.transferTo(tempFile);
        } catch (IOException e) {
            return Result.error().message("Failed to create or write to temporary file: " + e.getMessage());
        }

        // 使用 try-with-resources 确保 HttpClient 被正确关闭
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 创建多部分实体构建器
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("csv", tempFile);

            // 构建实体
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应实体
                HttpEntity responseEntity = response.getEntity();
                String responseBody = EntityUtils.toString(responseEntity);

                // 返回响应结果
                return Result.ok().data("data", responseBody);
            }
        } catch (IOException e) {
            return Result.error().message("Failed to execute HTTP request: " + e.getMessage());
        } finally {
            // 删除临时文件
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }
    @PostMapping("/useApispig")
    public Result useApispig(@RequestParam("file") MultipartFile file) {
        String url = "http://newvetai.world-tech.com.cn:8092/pigwarn/";

        // 创建临时文件
        File tempFile;
        try {
            tempFile = File.createTempFile("temp", null);
            file.transferTo(tempFile);
        } catch (IOException e) {
            return Result.error().message("Failed to create or write to temporary file: " + e.getMessage());
        }

        // 使用 try-with-resources 确保 HttpClient 被正确关闭
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpPost httpPost = new HttpPost(url);

            // 创建多部分实体构建器
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("csv", tempFile);

            // 构建实体
            HttpEntity multipart = builder.build();
            httpPost.setEntity(multipart);

            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                // 获取响应实体
                HttpEntity responseEntity = response.getEntity();
                String responseBody = EntityUtils.toString(responseEntity);

                // 返回响应结果
                return Result.ok().data("data", responseBody);
            }
        } catch (IOException e) {
            return Result.error().message("Failed to execute HTTP request: " + e.getMessage());
        } finally {
            // 删除临时文件
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }
}